<?php

namespace app\admin\controller\api;

use think\admin\Controller;
use think\admin\model\SystemQueue;
use think\admin\service\AdminService;
use think\admin\service\QueueService;
use think\exception\HttpResponseException;

/**
 * 任务监听服务管理
 * @class Queue
 * @package app\admin\controller\api
 */
class Queue extends Controller
{
  /**
     * 立即执行指定任务
     * @login true
     */
    public function dorun()
    {
        $taskId = $this->request->post('id');
        $taskInfo = SystemQueue::mQuery()->db()->where(['code' => $taskId])->find();
        $downloadId = json_decode($taskInfo['exec_data']);
        $this->_queue($taskInfo['title']."运行一次", $taskInfo['command'], 1,  $downloadId, 0);
    }
    /**
     * 停止监听服务
     * @login true
     */
    public function stop()
    {
        if (AdminService::isSuper()) try {
            $message = $this->app->console->call('xadmin:queue', ['stop'])->fetch();
            if (stripos($message, 'sent end signal to process')) {
                sysoplog('系统运维管理', '尝试停止任务监听服务');
                $this->success('停止任务监听服务成功！');
            } elseif (stripos($message, 'processes to stop')) {
                $this->success('没有找到需要停止的服务！');
            } else {
                $this->error(nl2br($message));
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        } else {
            $this->error('请使用超管账号操作！');
        }
    }

    /**
     * 启动监听服务
     * @login true
     */
    public function start()
    {
        if (AdminService::isSuper()) try {
            $message = $this->app->console->call('xadmin:queue', ['start'])->fetch();
            if (stripos($message, 'daemons started successfully for pid')) {
                sysoplog('系统运维管理', '尝试启动任务监听服务');
                $this->success('任务监听服务启动成功！');
            } elseif (stripos($message, 'daemons already exist for pid')) {
                $this->success('任务监听服务已经启动！');
            } else {
                $this->error(nl2br($message));
            }
        } catch (HttpResponseException $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            trace_file($exception);
            $this->error($exception->getMessage());
        } else {
            $this->error('请使用超管账号操作！');
        }
    }

    /**
     * 检查监听服务
     * @login true
     */
    public function status()
    {
        if (AdminService::isSuper()) try {
            $message = $this->app->console->call('xadmin:queue', ['status'])->fetch();
            if (preg_match('/process.*?\d+.*?running/', $message)) {
                echo "<span class='color-green pointer' data-tips-text='{$message}'>{$this->app->lang->get('已启动')}</span>";
            } else {
                echo "<span class='color-red pointer' data-tips-text='{$message}'>{$this->app->lang->get('未启动')}</span>";
            }
        } catch (\Error|\Exception $exception) {
            echo "<span class='color-red pointer' data-tips-text='{$exception->getMessage()}'>{$this->app->lang->get('异 常')}</span>";
        } else {
            $message = lang('只有超级管理员才能操作！');
            echo "<span class='color-red pointer' data-tips-text='{$message}'>{$this->app->lang->get('无权限')}</span>";
        }
    }

    /**
     * 查询任务进度
     * @login true
     * @throws \think\admin\Exception
     */
    public function progress()
    {
        $input = $this->_vali(['code.require' => '任务编号不能为空！']);
        $data = SystemQueue::mk()->where($input)->field('message,exec_desc,status')->find();

        $message = null;
        if(!empty($data)){
            if(strlen($data['message']) > 0){
                $message = $data['message'];
            }else if(strlen($data['exec_desc']) > 0){
                // fix：message是延迟写入的，还没写入就报错了，这样查看日志打开会显示空白&一直请求api.queue/progress接口，此处模拟一下message数据
                $message = json_encode([
                    "code"      =>  $input['code'],
                    "status"    =>  $data['status'],
                    "sctime"    =>  0,
                    "message"   =>  '>>> 任务处理失败 <<<',
                    "progress"  =>  "100.00",
                    "history"   =>  [
                        [
                            "message"  => "错误信息查看列表页的执行结果",
                            "progress" => "000.00",
                            "datetime" => "1970-01-01 00:00:00"
                        ]
                    ]
                ]);
            }
        }

        if (!empty($message)) {
            $res = json_decode($message, true);
            // fix：message是延迟写入的，exception中断的message里的status不对，暂时在这里改成对的返回
            if(isset($res['status'])){
                $res['status'] = $data['status'];
            }
            $this->success('获取任务进度成功！', $res);
        } else {
            $queue = QueueService::instance()->initialize($input['code']);
            $this->success('获取任务进度成功！', $queue->progress());
        }
    }
}